import json

from flask_restful.reqparse import RequestParser


class Page(object):
    """
        基于的分页组件
    """
    page_parser = RequestParser()
    page_parser.add_argument('page', type=int, default=1)  # 起送门槛
    page_parser.add_argument('size', type=int, default=10)  # 每页

    def __init__(self, sqlalchemy_query, object_class=None):
        """
        :param sqlalchemy_query:  sqlalchemy_query 查询语句
        """
        args = self.page_parser.parse_args()
        self.page = args["page"]  # 查询的页码
        self.size = args["size"]  # 每页的大小
        if object_class:
            sqlalchemy_query = sqlalchemy_query.order_by(object_class.id.desc())
        self.sqlalchemy_query = sqlalchemy_query.paginate(page=self.page,
                                                          per_page=self.size,
                                                          error_out=False,
                                                          max_per_page=50)

    def count(self):
        return self.sqlalchemy_query.count()

    def page_info(self):
        """
            分页信息, 目前前端只用到了 total 这个值
        """
        return {
            "total": self.sqlalchemy_query.total,
            "pages": self.sqlalchemy_query.pages,
            "page": self.sqlalchemy_query.page,
            "size": self.size
            # "has_next": self.sqlalchemy_query.has_next,
            # "has_prev": self.sqlalchemy_query.has_prev
        }

    @property
    def items(self):
        """
            返回查询的集合列表
        """
        items = self.sqlalchemy_query.items
        return items